package view.listeners;

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import model.Constants;
import model.HostAddress;
import model.Subnet;
import view.components.SubnetComboBox;
import view.views.dialogContentViews.IpListPanel;
import controller.Controller;

public class AddIpbyListListener implements ActionListener {

	private final Window comp;
	private final SubnetComboBox subnetCombo;

	public AddIpbyListListener(Window comp, SubnetComboBox subnetCombo) {
		this.comp = comp;
		this.subnetCombo = subnetCombo;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		IpListPanel ipList = Controller.getInstance().getIpList();

		if (ipList != null) {

		String s = ipList.getTextField().getText();
		String ip = null;

			ip = (String) ipList.getIpBox().getBox().getSelectedItem();


		if (s.equals(Constants.EMPTY) || s.equals(null)) {
			s = Constants.IPRESERVED;
		}

		if (!subnetCombo.getBox().getSelectedItem().equals(Constants.EMPTY)) {

				Subnet sub = subnetCombo.getMap().get(
						subnetCombo.getBox().getSelectedItem());
				ArrayList<HostAddress> hostList = Controller.getInstance()
						.getHosts();
				int indexHost = 0, indexSub = 0;
				for (HostAddress element : hostList) {
					for (Subnet subnet : element.getSubnetList()) {
						if (sub.getNetAdress().getAddress()
								.equals(subnet.getNetAdress().getAddress())) {
							hostList.get(indexHost).getSubnetList()
									.get(indexSub).editIpAddress(ip, s);
							Controller.getInstance().setHosts(hostList);
							comp.dispose();
						}
						indexSub++;
					}
					indexHost++;
					indexSub = 0;
				}


		}
		}

	}

}
